package lnk

import (
	"oa-rest/common"
	"xorm.io/xorm"
)

func queryUserLnk(username string) (lnks []*Lnk, err error) {
	if err = common.DB.SQL("select t2.* from user_lnk t1 left join lnk t2 on t1.lnk_id=t2.id where t1.username = ? order by t1.id asc", username).Find(&lnks); err != nil {
		return
	}

	// 如果为空，则从user的第一个部门默认模板中获取，并写入lnkuser
	if len(lnks) == 0 {
		var orgId int64
		if _, err = common.DB.SQL("select org_id from us_user_organization where user_id = ? limit 1", username).Get(&orgId); err != nil {
			return
		}
		if orgId == 0 {
			return
		} else {
			if err = common.DB.SQL("select t2.* from org_lnk t1 left join lnk t2 on t1.lnk_id=t2.id where t1.org_id = ?", orgId).Find(&lnks); err != nil {
				return
			}

			userLnks := make([]*UserLnk, 0)
			for _, lnk := range lnks {
				userLnks = append(userLnks, &UserLnk{Username: username, LnkId: lnk.Id})
			}

			if _, err = common.DB.Insert(&userLnks); err != nil {
				return
			}
		}
	}
	return
}

// 获取所有快捷操作卡片
func getAllLnk() (lnks []*Lnk, err error) {
	err = common.DB.SQL("SELECT * FROM lnk ORDER BY \"order\"").Find(&lnks)
	return
}

// 更新用户快捷操作排序
func updateUserLnkOrder(username string, lnkIds []int64) error {

	_, err := common.DB.Transaction(func(session *xorm.Session) (interface{}, error) {
		// 删除原有排序
		if _, err := session.Exec("DELETE FROM user_lnk WHERE username = ?", username); err != nil {
			return err, nil
		}

		// 按新顺序插入
		newLnks := make([]*UserLnk, 0)
		for _, lnkId := range lnkIds {
			userLnk := &UserLnk{
				Username: username,
				LnkId:    lnkId,
			}
			newLnks = append(newLnks, userLnk)
		}
		if _, err := session.Insert(newLnks); err != nil {
			return err, nil
		}
		return nil, nil
	})
	return err
}
